package com.dmz.czykt.util;

import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;
import org.bouncycastle.util.encoders.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.security.Key;
import java.security.Security;
import java.util.Arrays;
import java.util.UUID;


/**
 * @author lee
 * @date 2020-03-23 10:9:49
 */
@Slf4j
public class EncryptUtil {
    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    private static final String ENCODING = "UTF-8";//
    public static final String GB18030 = "GB18030";
    public static final String ALGORITHM_NAME = "SM4";
    // 加密算法/分组加密模式/分组填充方式
    // PKCS5Padding-以8个字节为一组进行分组加密
    // 定义分组加密模式使用：PKCS5Padding
    public static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS5Padding";

    /**
     * 生成ECB暗号
     *
     * @param algorithmName 算法名称
     * @param mode          模式
     * @param key
     * @return
     * @throws Exception
     * @explain ECB模式（电子密码本模式：Electronic codebook）
     */
    private static Cipher generateEcbCipher(String algorithmName, int mode,
                                            byte[] key) throws Exception {
        Cipher cipher = Cipher.getInstance(algorithmName,
                BouncyCastleProvider.PROVIDER_NAME);
        Key sm4Key = new SecretKeySpec(key, ALGORITHM_NAME);
        cipher.init(mode, sm4Key);
        return cipher;
    }


    /**
     * sm4加密
     *
     * @param hexKey   16进制密钥（忽略大小写）
     * @param paramStr 待加密字符串
     * @return 返回base64编码的加密字符串
     * @throws Exception
     * @explain 加密模式：ECB 密文长度不固定，会随着被加密字符串长度的变化而变化
     */
    public static String encryptEcb(String hexKey, String paramStr, String encoding)
            throws Exception {
        String cipherText = "";
        // 16进制字符串-->byte[]
        byte[] keyData = ByteUtils.fromHexString(hexKey);
//		System.out.println(keyData.length);
        // String-->byte[]
        byte[] srcData = paramStr.getBytes(encoding);
        // 加密后的数组
        byte[] cipherArray = encrypt_Ecb_Padding(keyData, srcData);
        // byte[]-->base64String
        cipherText = new String(Base64.encode(cipherArray));
//		cipherText = ByteUtils.toHexString(cipherArray);
        return cipherText;
    }

    public static String encryptEcb(String hexKey, String paramStr) throws Exception {
        return encryptEcb(hexKey, paramStr, GB18030);
    }

    /**
     * 加密模式之Ecb
     *
     * @param key
     * @param data
     * @return
     * @throws Exception
     * @explain
     */
    public static byte[] encrypt_Ecb_Padding(byte[] key, byte[] data)
            throws Exception {
        Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING,
                Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(data);
    }

    /**
     * sm4解密
     *
     * @param hexKey     16进制密钥
     * @param cipherText base64编码的加密字符串
     * @return 解密后的字符串
     * @throws Exception
     * @explain 解密模式：采用ECB
     */
    public static String decryptEcb(String hexKey, String cipherText, String encoding)
            throws Exception {
        // 用于接收解密后的字符串
        String decryptStr = "";

        // hexString-->byte[]
        byte[] keyData = ByteUtils.fromHexString(hexKey);
        // base64String-->byte[]
        byte[] cipherData = Base64.decode(cipherText);
        // 解密
        byte[] srcData = decrypt_Ecb_Padding(keyData, cipherData);
        // byte[]-->String
        decryptStr = new String(srcData, encoding);
        return decryptStr;
    }

    public static String decryptEcb(String hexKey, String cipherText)
            throws Exception {
        return decryptEcb(hexKey, cipherText, GB18030);
    }

    /**
     * 解密
     *
     * @param key
     * @param cipherText
     * @return
     * @throws Exception
     * @explain
     */
    public static byte[] decrypt_Ecb_Padding(byte[] key, byte[] cipherText)
            throws Exception {
        Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING,
                Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(cipherText);
    }

    /**
     * 校验加密前后的字符串是否为同一数据
     *
     * @param hexKey     16进制密钥（忽略大小写）
     * @param cipherText base64编码加密后的字符串
     * @param paramStr   加密前的字符串
     * @return 是否为同一数据
     * @throws Exception
     * @explain
     */
    public static boolean verifyEcb(String hexKey, String cipherText,
                                    String paramStr) throws Exception {
//		BASE64Decoder decoder = new BASE64Decoder();
        // 用于接收校验结果
        boolean flag = false;
        // hexString-->byte[]
        byte[] keyData = ByteUtils.fromHexString(hexKey);
        // 将base64编码字符串转换成数组
        byte[] cipherData = Base64.decode(cipherText);
        // 解密
        byte[] decryptData = decrypt_Ecb_Padding(keyData, cipherData);
        // 将原字符串转换成byte[]
        byte[] srcData = paramStr.getBytes(ENCODING);
        // 判断2个数组是否一致
        flag = Arrays.equals(decryptData, srcData);
        return flag;
    }

    /**
     * 测试
     */
    public static void main(String[] args) {
        try {
            String json = "测试文字";
            // 自定义的32位 16进制密钥
            String key = UUID.randomUUID().toString().replace("-", "");
            System.out.println("密钥： " + key);
//			String key = "4A65463855397748464F4D6673325938";
//			加密
            String cipher = encryptEcb(key, json);
            System.out.println("加密后：" + cipher);
//			解密
            String decrypt = decryptEcb(key, cipher);
            System.out.println("解密后：" + decrypt);


            String filePath = "D:\\report\\yh005_140000000000_140000000000To402161002352_846eec31a0ab4572a4980406d0a5a85c.txt";
//			 filePath="	D:\\czykt\\out\\yh010_140000000000_140105000000To402161002352_b72d404e600f471d938c6d69941d998e.txt";
            String fileName = "yh010_140000000000_140105000000To402161002352_b72d404e600f471d938c6d69941d998e.txt";
//			PE.GLNT.03531.0000019735.502.T0320.RET.123456789641234.太原市社会保险中心.中国建设银行山西省分行.103045578524
            encryptEcbTxt(filePath, "AF4519E9CBBC41D99F51E1800A0C318D");
//			readTxtYH010de(filePath,"AF4519E9CBBC41D99F51E1800A0C318D");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean readTxtGB218030(String file) {
        FileInputStream fileisr;
        try {
            fileisr = new FileInputStream(FileUtil.newFile(file));
            int datalength = fileisr.available();
            byte[] buff = new byte[datalength];
            int length = fileisr.read(buff);
            String json = new String(buff, 0, length);
//			解密
            System.out.println(file + "：开始转码GB18030");
			//读文件
            File f = FileUtil.newFile(file);
            BufferedWriter output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), GB18030));//创建流（拿个笔）
            output.write(json);//写文件内容
            output.close();//关闭流 （把笔放了）
            return true;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
    }

    public static boolean readTxtYH010de(String file, String key) {
        FileInputStream fileisr;
        try {
            File sf = FileUtil.newFile(file);
            fileisr = new FileInputStream(sf);
            int datalength = fileisr.available();
            byte[] buff = new byte[datalength];
            int length = fileisr.read(buff);
            String json = new String(buff, 0, length);
//			解密
            String decrypt = decryptEcb(key, json);
            System.out.println("解密后：" + decrypt);
            File f = FileUtil.newFile(file);//读文件
            BufferedWriter output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), ENCODING));//创建流（拿个笔）
            output.write(decrypt + "");//写文件内容
            output.close();//关闭流 （把笔放了）
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    public static void encryptEcbTxt(String file, String key) {
        FileInputStream fileisr;
        try {
            fileisr = new FileInputStream(FileUtil.newFile(file));
            int datalength = fileisr.available();
            byte[] buff = new byte[datalength];
            int length = fileisr.read(buff);
            String json = new String(buff, 0, length);
//			加密
            String cipher = encryptEcb(key, json);
            System.out.println("加密后：" + cipher);
            File f = FileUtil.newFile(file);//读文件
            BufferedWriter output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f)));//创建流（拿个笔）
            output.write(cipher + "");//写文件内容
            output.close();//关闭流 （把笔放了）
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}